package com.fingard.dsp.bank.directbank.bocz01;


import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class BOCZ01SinglePay extends BOCZ01Base implements ISinglePay {

    //单笔支付，不需采用流处理方式
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail;
        tmpRetDetail = externalPayments(p_req1908);
        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    //190802对外支付
    private RetAtsSglDetail externalPayments(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        if ("190801".equals(p_req1908.reqHeader.commandCode)) {
            bankInnerTransfer(p_req1908, retDetail);
        } else {
            if (p_req1908.singleDetail.sameBnk.equals("1")) {//同行
                bankInnerTransfer(p_req1908, retDetail);
            } else {//跨行
                crossBankTransfer(p_req1908, retDetail);
            }
        }
        return retDetail;
    }

    //同行支付
    private RetAtsSglDetail bankInnerTransfer(ReqSingle p_req1908, RetAtsSglDetail retDetail) throws Exception {
        serviceId = "190801".equals(p_req1908.reqHeader.commandCode) ? "CBE020101" : "CBE020102";//内部转账和同行转账
        serialNo = p_req1908.reqHeader.reqSeqID;
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入报文头部信息
        writeCommonHeader(xmlWriter);
        //需要进行对账码拼接以及节点解析，采用XElement进行处理
        //单笔、批量共用节点赋值方法
        XElement tmpXElement = new XElement("ReqParam", "");
        tmpXElement.addChild(new XElement("payAccount", p_req1908.singleDetail.payAct));
        tmpXElement.addChild(new XElement("payAccountName", p_req1908.singleDetail.payName));
        tmpXElement.addChild(new XElement("payAmount", p_req1908.singleDetail.payAmount));
        tmpXElement.addChild(new XElement("payUse", p_req1908.singleDetail.abstractATS));
        tmpXElement.addChild(new XElement("recAccount", p_req1908.singleDetail.recAct));
        tmpXElement.addChild(new XElement("recAccountName", p_req1908.singleDetail.recName));
        tmpXElement.addChild(new XElement("orderFlowNo", "ZJSH"+serialNo.toLowerCase()));
        nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
        xmlWriter.writeXElement(tmpXElement);
        xmlWriter.writeEndDocument();//报文结束
        String dataConvert = xmlWriter.toXmlString();
        int index = dataConvert.indexOf("?>");
        String data = dataConvert.substring(0, index + 2) + "\r\n" + clearLineWrapAndBlank(dataConvert.substring(index + 2));
        //发送给银行的签名端口进行签名
        String[] tmpSign = sendToBankSignXml(data);
        if (tmpSign[0].length() == 0) {
            String body = "";
            String aa = "<result>";
            int i = tmpSign[1].indexOf(aa);
            if (i != -1) {
                body = tmpSign[1].substring(i + 8, i + 9);
            }
            if (body.equals("0")) {
                String ab = "<sign>";
                String ac = "</sign>";
                int ib = tmpSign[1].indexOf(ab);
                int ic = tmpSign[1].indexOf(ac);
                //以下为最终的签名结果
                signature = clearLineWrapAndBlank(tmpSign[1].substring(ib + 6, ic));
                String[] tmpStrRet = sendToBank(data);//发送给银行
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    //解析银行返回
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("#") + 1), tmpSbMsg);
                    if (tmpBkReader != null) {
                        String retCode = tmpBkReader.getFirstText("/BankData/opRep/opResult/retCode");//失败才返回此节点
                        String errorMsg = tmpBkReader.getFirstText("/BankData/opRep/opResult/retMessage");
                        retDetail.respCode = "0";
                        retDetail.respInfo = errorMsg;
                        retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        retDetail.transState = tmpBkReader.getFirstText("/BankData/opRep/opResult/orderState");
                        retDetail.payInfoCode = retDetail.transState;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpSbMsg.toString();
                    }
                } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                    retDetail.respCode = "0";
                    retDetail.respInfo = tmpStrRet[1];
                    retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    retDetail.transState = PaymentState.FAIL_Payment;
                    retDetail.payInfoCode = tmpStrRet[0];
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpStrRet[1];
                }
            } else {//签名数据返回数据为空
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSign[1];
            }
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpSign[1];
        }
        return retDetail;
    }

    //跨行支付
    private RetAtsSglDetail crossBankTransfer(ReqSingle p_req1908, RetAtsSglDetail retDetail) throws Exception {
        serviceId = "CBE020103";
        serialNo = p_req1908.reqHeader.reqSeqID;
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter);
        //需要进行对账码拼接以及节点解析，采用XElement进行处理
        //单笔、批量共用节点赋值方法
        XElement tmpXElement = new XElement("ReqParam", "");
        tmpXElement.addChild(new XElement("payAccount", p_req1908.singleDetail.payAct));
        tmpXElement.addChild(new XElement("payAccountName", p_req1908.singleDetail.payName));
        tmpXElement.addChild(new XElement("currencyType", convertCurToBank(p_req1908.singleDetail.payCur)));
        tmpXElement.addChild(new XElement("payAmount", p_req1908.singleDetail.payAmount));
        tmpXElement.addChild(new XElement("payUse", p_req1908.singleDetail.abstractATS));
        tmpXElement.addChild(new XElement("recAccount", p_req1908.singleDetail.recAct));
        tmpXElement.addChild(new XElement("recAccountName", p_req1908.singleDetail.recName));
        tmpXElement.addChild(new XElement("unionBankNo", p_req1908.singleDetail.cnapsCode));
        tmpXElement.addChild(new XElement("chargeFee", "0.00"));
        String trsMode = "0";
        if (Float.parseFloat(p_req1908.singleDetail.payAmount) > 20000) {//两万以上走大额
            trsMode = "1";
        } else if (p_req1908.singleDetail.paySpd.equals("1")) {//加急走大额
            trsMode = "1";
        } else {
            trsMode = "0";
        }
        tmpXElement.addChild(new XElement("payMethodType", trsMode));
        tmpXElement.addChild(new XElement("currIden", "0"));//钞汇标志 默认为0
        tmpXElement.addChild(new XElement("orderFlowNo", "ZJSH"+serialNo.toLowerCase()));
        nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
        xmlWriter.writeXElement(tmpXElement);
        xmlWriter.writeEndDocument();//写入报文完成
        String dataConvert = xmlWriter.toXmlString();
        int index = dataConvert.indexOf("?>");
        String data = dataConvert.substring(0, index + 2) + "\r\n" + clearLineWrapAndBlank(dataConvert.substring(index + 2));
        //发送给银行的签名端口进行签名
        String[] tmpSign = sendToBankSignXml(data);
        if (tmpSign[0].length() == 0) {
            String body = "";
            String aa = "<result>";
            int i = tmpSign[1].indexOf(aa);
            if (i != -1) {
                body = tmpSign[1].substring(i + 8, i + 9);
            }
            if (body.equals("0")) {
                String ab = "<sign>";
                String ac = "</sign>";
                int ib = tmpSign[1].indexOf(ab);
                int ic = tmpSign[1].indexOf(ac);
                //以下为最终的签名结果
                signature = clearLineWrapAndBlank(tmpSign[1].substring(ib + 6, ic));
                String[] tmpStrRet = sendToBank(data);//发送银行
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("#") + 1), tmpSbMsg);
                    if (tmpBkReader != null) {
                        String retCode = tmpBkReader.getFirstText("/BankData/opRep/opResult/retCode");
                        String errorMsg = tmpBkReader.getFirstText("/BankData/opRep/opResult/retMessage");
                        retDetail.respCode = "0";
                        retDetail.respInfo = errorMsg;
                        retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        retDetail.transState = tmpBkReader.getFirstText("/BankData/opRep/opResult/orderState");
                        retDetail.payInfoCode = retDetail.transState;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpSbMsg.toString();
                    }
                } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                    retDetail.respCode = "0";
                    retDetail.respInfo = tmpStrRet[1];
                    retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    retDetail.transState = PaymentState.FAIL_Payment;
                    retDetail.payInfoCode = tmpStrRet[0];
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpStrRet[1];
                }
            } else {//签名数据返回数据为空
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSign[1];
            }
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpSign[1];
        }
        return retDetail;
    }

    //1944 状态查询
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);

        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        serviceId = "CBE010106";
        serialNo = p_req1944.reqHeader.reqSeqID;
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter);
        xmlWriter.writeStartElement("ReqParam");
        xmlWriter.writeElementString("orderFlowNo",  "ZJSH"+reqHeader.reqSeqID.toLowerCase());
        // 行外：DP行内：BN
        String busiType = "BN";
        if(!"".equals(p_req1944.sameBnk)) {
            if(p_req1944.sameBnk.equals("1")) {
                xmlWriter.writeElementString("busiType", "BN");
            } else{
                xmlWriter.writeElementString("busiType", "DP");
            }
        }else{
            xmlWriter.writeElementString("busiType", busiType);
        }
        /*xmlWriter.writeElementString("busiType", p_req1944.payBankCode.equals(p_req1944.recBankCode)?"BN":"DP");//行外：DP行内：BN*/
        xmlWriter.writeEndDocument();
        try {
            String dataConvert = xmlWriter.toXmlString();
            int index = dataConvert.indexOf("?>");
            String data = dataConvert.substring(0, index + 2) + "\r\n" + clearLineWrapAndBlank(dataConvert.substring(index + 2));
            //发送给银行的签名端口进行签名
            String[] tmpSign = sendToBankSignXml(data);
            if (tmpSign[0].length() == 0) {
                String body = "";
                String aa = "<result>";
                int i = tmpSign[1].indexOf(aa);
                if (i != -1) {
                    body = tmpSign[1].substring(i + 8, i + 9);
                }
                if (body.equals("0")) {
                    String ab = "<sign>";
                    String ac = "</sign>";
                    int ib = tmpSign[1].indexOf(ab);
                    int ic = tmpSign[1].indexOf(ac);
                    //以下为最终的签名结果
                    signature = clearLineWrapAndBlank(tmpSign[1].substring(ib + 6, ic));
                    String[] tmpStrRet = sendToBank(data);
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("#") + 1), tmpSbMsg);
                        if (tmpBkReader != null) {
                            String retCode = tmpBkReader.getFirstText("/BankData/opRep/opResult/retCode");
                            String errorMsg = tmpBkReader.getFirstText("/BankData/opRep/opResult/retMessage");
                            if (retCode != null && isActiveRetCode(retCode)) {
                                while (tmpBkReader.read("/BankData/opRep/opResult")) {
                                    //行内如下F：失败S：成功L：处理中行外如下0：成功1：失败2：处理中
                                    String state = tmpBkReader.readedXElement.getSingleText("orderState");
                                    String code = tmpBkReader.readedXElement.getSingleText("retCode");
                                    retDetail.respCode = "0";
                                    retDetail.respInfo = tmpBkReader.readedXElement.getSingleText("retMessage");
                                    ;
                                    retDetail.payInfoCode = code + "+" + state;
                                    retDetail.transState = code + "+" + state;
                                    retDetail.reqSeqID = p_req1944.askNumber;
                                }
                            } else {
                                retDetail.respCode = "-1";
                                retDetail.respInfo = errorMsg;
                            }
                        } else {
                            retDetail.respCode = "-1";
                            retDetail.respInfo = tmpSbMsg.toString();
                        }
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpStrRet[1];
                    }
                } else {//签名数据返回数据为空
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSign[1];
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSign[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
